package com.atguigu.yygh.hosp.lisetener;

import com.atguigu.yygh.hosp.repository.ScheduleRepository;
import com.atguigu.yygh.hosp.service.ScheduleService;
import com.atguigu.yygh.model.hosp.Schedule;
import com.atguigu.yygh.rabbitmq.constant.RabbitMQConstant;
import com.atguigu.yygh.rabbitmq.service.RabbitMQService;
import com.atguigu.yygh.vo.msm.MsmVo;
import com.atguigu.yygh.vo.order.OrderMqVo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author:hx
 * @DateTime:2022/11/18 18:13
 * @Description:
 */
@Component
public class HospListener {

    @Autowired
    private RabbitMQService rabbitMQService;
    @Autowired
    private ScheduleService scheduleService;
    @Autowired
    private ScheduleRepository scheduleRepository;

    @RabbitListener(bindings = {
            @QueueBinding(
                    exchange = @Exchange(value = RabbitMQConstant.EXCHANGE_DIRECT_ORDER),
                    value = @Queue(value = RabbitMQConstant.QUEUE_ORDER),
                    key = {RabbitMQConstant.ROUTING_ORDER}
            )
    })
    public void listenMessage(OrderMqVo orderMqVo, Message message, Channel channel){
        if (orderMqVo.getAvailableNumber() == null){
            String scheduleId = orderMqVo.getScheduleId();
            String[] split = scheduleId.split(" ");
            Schedule schedule = scheduleRepository.getByHoscodeAndDepcodeAndHosScheduleId(split[0], split[1], split[2]);
            scheduleService.updateAvailableNumber(schedule.getId(),(schedule.getAvailableNumber() + 1));
        }else {
            scheduleService.updateAvailableNumber(orderMqVo.getScheduleId(),orderMqVo.getAvailableNumber());
        }
        MsmVo msmVo = orderMqVo.getMsmVo();
        if (msmVo != null){
            rabbitMQService.sendMessage(RabbitMQConstant.EXCHANGE_DIRECT_SMS,RabbitMQConstant.ROUTING_SMS,msmVo);
        }
    }
}
